import os
import sys

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from typing import List
from src.tasks.enterprise.EntEnterprise import EntEnterprise

class SyncSecuritiesData:
    def __init__(self, logger, localDb, fcdb):
        self.logger = logger
        self.localDb = localDb
        self.fcdb = fcdb
        self.size = 1000

    # 抽取待更新主体名单
    def __queryLocal__(self):
        sql = "select id, credit_code, comp_code from ent_enterprise where classify_type=0"
        return self.localDb.Query(sql)

    # 抽取存续债数据
    def __querySecurities__(self):
        sql = """
            SELECT  ISSUECOMPCODE, COUNT(1) AS cnt, SUM(CURRENTAMT) AS amt from (
                SELECT ISSUECOMPCODE, SECURITYID, CURRENTAMT  FROM tq_bd_newestbasicinfo 
                WHERE  MATURITYDATE >= CURRENT_DATE()
                AND ISVALID = 1 AND BONDTYPE1 IN ('5','6') AND BONDTYPE2 NOT IN('511','512')
                GROUP BY ISSUECOMPCODE, SECURITYID
                ) t 
            GROUP BY t.ISSUECOMPCODE;
            """
        return self.fcdb.Query(sql)

    # 同步入口
    def update(self, enterpriseList: List[EntEnterprise]):
        self.logger.info("更新存续债信息 开始")

        self.logger.info("待更新主体：%d" % len(enterpriseList))

        self.logger.info("查询存续债")
        secInfos = self.__querySecurities__()
        secInfos = {d["ISSUECOMPCODE"]: d for d in secInfos}
        self.logger.info("查询存续债：%d" % len(secInfos))

        for ent in enterpriseList:
            if ent.comp_code in secInfos.keys():
                secInfo = secInfos.get(ent.comp_code)
                ent.debt_num = secInfo["cnt"]
                ent.debt_scale = secInfo["amt"]

        self.logger.info("更新存续债信息 完成")
